/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */

package org.openmrs.module.clinicalsummary.predicate;

import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.util.OpenmrsUtil;

public abstract class BasePredicate implements Predicate {

	private static final Log log = LogFactory.getLog(BasePredicate.class);

	private String property;

	private Class type;

	private Object value;

	protected Set<String> properties;

	/**
	 * Get the property on which this predicate should be evaluated
	 *
	 * @return the property
	 */
	public String getProperty() {
		return property;
	}

	/**
	 * Set the property on which the predicate should be evaluated
	 *
	 * @param property the property
	 */
	public void setProperty(final String property) {
		this.property = property;
	}

	/**
	 * Get the expected type of the property
	 *
	 * @return the type of the property
	 */
	public Class getType() {
		return type;
	}

	/**
	 * Set the expected type of the property
	 *
	 * @param type the type of the property
	 */
	public void setType(final Class type) {
		this.type = type;
	}

	/**
	 * Get the expected value of the property
	 *
	 * @return the expected value
	 */
	public Object getValue() {
		return value;
	}

	/**
	 * Set the expected value of the property
	 *
	 * @param value the expected value
	 */
	public void setValue(final Object value) {
		this.value = value;
	}

	/**
	 * Check whether a property is supported by the predicate or not
	 *
	 * @param propertyName the property name to be checked
	 * @return true if the predicate support evaluation on the property
	 */
	public Boolean supportedProperty(final String propertyName) {
		return properties.contains(propertyName);
	}

	/**
	 * Evaluate the predicate on the object and return true if the object conform to the predicate
	 *
	 * @param object object where the predicate should be evaluated
	 * @return true if the expected value of the property match the value in this predicate
	 */
	public Boolean evaluate(final Object object) {
		Object propertyValue = null;
		try {
			propertyValue = PropertyUtils.getProperty(object, getProperty());
		} catch (Exception e) {
			log.error("Reading " + getProperty() + " from the object in the parameter failed!", e);
		}
		return OpenmrsUtil.nullSafeEquals(propertyValue, getValue());
	}
}
